<?php
require_once 'init_app.php';

set_time_limit(0);

$products = ORM::factory('product')
            ->where('is_image', '=', 0)
            ->where('is_available', '=', 1)
            ->limit(100000)
            ->find_all();

foreach ($products as $product) {   
    try { 
        $dir = APPPATH.'../media/uploads/products/';
        $dir = $dir.sprintf('%02x/', $product->id % 0xff);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $dir = $dir.sprintf('%02x/', $product->id % 0xcf);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $dir = $dir.sprintf('%02x/', $product->id % 0x8f);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $dir = $dir.sprintf('%02x/', $product->id % 0x4f);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $dir = $dir.sprintf('%d/', $product->id);
        if (!is_dir($dir)) {
            mkdir($dir);
        }

        $filename = $dir.$product->id.'.jpg';
        $data = file_get_contents($product->picture);
        $f = fopen($filename, 'w+');
        fputs($f, $data);
        fclose($f);

        $image = Image::factory($filename); 
        $image->resize(400, null)->save();
        
        $product->is_image = 1;
        $product->save();
    } catch (Exception $e) {
        //echo $e->getMessage();
        //die();
        continue;
    }
}
